import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { NulResponse, createEmptyRequest, createRequest } from "./common";
import { RootState } from "./store";
import { cloneArray } from "../util/Arrays";
import { getRequest } from "../util/Auth";

interface CommodityEntry {
  id: number;
  name: string;
  wholesalePrice: number;
  retailPrice: number;
  costPrice: number;
  notes: string;
}

interface CommodityState {
  fetched: boolean;
  entries: CommodityEntry[];
}

interface CommodityRequest {
  name: string;
  wholesalePrice: number;
  retailPrice: number;
  costPrice: number;
  notes: string;
}

interface CreateCommodityResponse {
  id: number;
}

interface CommodityDeleteRequest {
  id: number[];
}

const commodityInitialState: CommodityState = {
  fetched: false,
  entries: []
};

export const fetchAllCommodityEntries = createAsyncThunk('api/fetchAllCommodityEntries', async (_, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CommodityEntry[]>>('/service/commodity/fetchAll',
      createEmptyRequest());
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const createNewCommodity = createAsyncThunk('api/createNewCommodity', async (commodity: CommodityRequest, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CreateCommodityResponse>>('/service/commodity/createEntry',
      createRequest(commodity));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const modifyCommodity = createAsyncThunk('api/modifyCommodity', async (commodity: CommodityEntry, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('/service/commodity/modifyEntry', createRequest(commodity));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const deleteCommodity = createAsyncThunk('api/deleteCommodity', async (commoditys: number[], { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('/service/commodity/deleteEntry',
      createRequest<CommodityDeleteRequest>({ id: commoditys }));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});



const commoditySlice = createSlice({
  name: 'commodity',
  initialState: commodityInitialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(fetchAllCommodityEntries.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(fetchAllCommodityEntries.fulfilled, (state, action) => {
      state.fetched = true;
      state.entries = action.payload.result;
    }).addCase(createNewCommodity.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(createNewCommodity.fulfilled, (state, action) => {
      console.log(action.payload);
      const entry: CommodityEntry = {
        ...action.meta.arg,
        ...action.payload.result
      };
      state.entries.push(entry);
      state.entries.sort((a, b) => a.id - b.id);
    }).addCase(modifyCommodity.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(modifyCommodity.fulfilled, (state, action) => {
      const index: number = state.entries.findIndex(item => item.id === action.meta.arg.id);
      if (index !== -1) {
        state.entries[index] = action.meta.arg;
      }
    }).addCase(deleteCommodity.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(deleteCommodity.fulfilled, (state, action) => {
      const deletedIds: number[] = cloneArray(action.meta.arg);
      const commodityEntries: CommodityEntry[] = state.entries;
      deletedIds.sort();
      const result: CommodityEntry[] = [];
      for (let i = 0, j = 0; j < commodityEntries.length; ++j) {
        if (commodityEntries[j].id !== deletedIds[i])
          result.push(commodityEntries[j]);
        else ++i;
      }
    });
  }
});



export type { CommodityEntry };
export const { actions } = commoditySlice;
export const selectCommodityEntries = (state: RootState) => state.commodityInformationReducer.entries;
export const selectCommodityFetched = (state: RootState) => state.commodityInformationReducer.fetched;
export default commoditySlice.reducer;